package org.jvm.rtda.heap.classmember;

import org.jvm.classfile.MemberInfo;
import org.jvm.classfile.attributeinfo.ConstantValueAttribute;
import org.jvm.rtda.heap.Klass;
import org.jvm.rtda.heap.classLoader.KlassLoaderRegister;
import org.jvm.rtda.thread.Thread;
import org.jvm.util.JvmUtil;

/**
 * 类字段信息
 *
 * @author 王思翔
 * @date 2023/2/4
 */
public class Field extends ClassMember {

    /**
     * 字段位于类字段空间中的坐标
     */
    private int slotId;

    /**
     * 字段初始值在常量池中的坐标
     */
    private int constValueIndex;

    public int getSlotId() {
        return slotId;
    }

    public void setSlotId(int slotId) {
        this.slotId = slotId;
    }

    public int getConstValueIndex() {
        return constValueIndex;
    }

    public void setConstValueIndex(int constValueIndex) {
        this.constValueIndex = constValueIndex;
    }

    public Field(Klass klass, MemberInfo memberInfo) {
        super(klass, memberInfo);
        ConstantValueAttribute constantValueAttribute = memberInfo.getConstantValueAttribute();
        if (constantValueAttribute != null) {
            this.constValueIndex = constantValueAttribute.getConstantValueIndex();
        }
    }

    public boolean isLongOrDouble() {
        return this.descriptor.equals("J") || this.descriptor.equals("D");
    }

    public Klass getType(Thread thread) {
        String className = JvmUtil.toClassName(this.descriptor);
        return KlassLoaderRegister.loadKlass(className, thread);
    }
}
